<?php


namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\meeting\Info as InfoModel;
use \app\admin\model\department\Department as DepartmentModel;
use \app\admin\model\department\Admin as DepartmentAdminModel;
use app\admin\model\user\party\Member;
use \app\admin\model\meeting\Attendees as AttendeesModel;
use \app\admin\model\meeting\Minutes as MinutesModel;
use \app\admin\model\meeting\Notifications as NotificationsModel;
use app\common\model\User;

class Meeting extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }



    /**
     * 获取党支部ID
     */
    public function getDepartmentId($id)
    {
        $DepartmentAdmin = DepartmentAdminModel::where('admin_id', $id)->find();
        $Department = DepartmentModel::where('id', $DepartmentAdmin->department_id)->select();
        $Department1 = $Department[0];
        if ($Department1->group_id == null) {
            $Department2 = DepartmentModel::where('parent_id', $Department1->id)->select();
            $asd = [];
            foreach ($Department2 as $key => $value) {
                $asd[] = $value->id;
            }
            $Department = DepartmentModel::where('parent_id', "in", $asd)->select();
        } else if ($Department1->group_id == 3) {
            $Department = DepartmentModel::where('parent_id', $Department1->id)->select();
        }
        $qwe = [];
        foreach ($Department as $key => $value) {
            $qwe[] = $value->id;
        }
        $this->success('获取成功', $qwe);
    }



    /**
     * 获取党支部
     */
    public function getDepartment($ids, $name = null)
    {
        $ids = explode(",", $ids);
        // 
        if ($name == null) {
            $Department = DepartmentModel::where('id', "in", $ids)->select();
        } else {
            $Department = DepartmentModel::where('id', "in", $ids)->where(DepartmentModel::getTable() . ".name", "like", "%$name%")->select();
        }
        foreach ($Department as $key => $value) {
            $value->state = true;
        }
        $this->success('获取成功', $Department);
    }

    /**
     * 新建会议
     */
    public function submit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            // $this->success('提交成功', $params);
            $params['start_time'] = (int)($params['start_time'] / 1000);
            $params['end_time'] = (int)($params['end_time'] / 1000);
            $params['user_id'] = $this->auth->id;
            $params['create_time'] = time();
            $departments = json_decode(html_entity_decode($params['departments']), true);
            if (count($departments) > 0) {
                $asd = [];
                $qwe = [];
                foreach ($departments as $key => $value) {
                    $userList = Member::where("thee_department_id", $value["id"])->select();
                    $qwe[] = $userList;
                    $asd[] = $value["id"];
                }
                $params['de_id'] = implode(', ', $asd);;
            }

            $params['type'] = $params['type_id'];
            unset($params['type_id']);
            unset($params['departments']);
            unset($params['department']);
            unset($params['typename']);
            $record = InfoModel::insert($params);
            if ($record) {
                $meeting = InfoModel::where($params)
                    ->find();
                foreach ($qwe as $key => $value) {
                    foreach ($qwe[$key] as $ke => $valu) {
                        $zxc = [
                            "meeting_id" => $meeting->id,
                            "user_id" => $valu->user_id,
                            "create_time" => time()
                        ];
                        AttendeesModel::insert($zxc);
                    }
                }
                $this->success('提交成功');
            }
            $this->error('提交失败');
        }
        $this->error('非法请求');
    }


    /**
     * 获取线上会议列表
     *
     */
    public function list($type)
    {
        if ($type == 1) {
            $list = InfoModel::where("type", 1)
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info, $key) {
                    $info->user = User::get(["id" => $info->user_id]);
                    $info->is_creator = false;
                    if ($info->user_id == $this->auth->id) {
                        $info->is_creator = true;
                    }
                    $info->user_num = AttendeesModel::where('meeting_id', $info->id)
                        ->group('user_id')
                        ->count();
                });
        } else if ($type == 2) {
            $startOfDay = strtotime('today');
            $endOfDay = strtotime('tomorrow') - 1;
            $list = InfoModel::where('user_id', $this->auth->id)
                ->where('start_time', '>', $startOfDay)
                ->where('start_time', '<', $endOfDay)
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info, $key) {
                    $info->user = User::get(["id" => $info->user_id]);
                    $info->is_creator = false;
                    if ($info->user_id == $this->auth->id) {
                        $info->is_creator = true;
                    }
                    $info->user_num = AttendeesModel::where('meeting_id', $info->id)
                        ->group('user_id')
                        ->count();
                });
        } else if ($type == 3) {
            $list = InfoModel::with(['attendees' => function ($query) {
                $query->where('user_id', $this->auth->id);
            }])
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info, $key) {
                    $info->user = User::get(["id" => $info->user_id]);
                    $info->is_creator = false;
                    if ($info->user_id == $this->auth->id) {
                        $info->is_creator = true;
                    }
                    $info->user_num = AttendeesModel::where('meeting_id', $info->id)
                        ->group('user_id')
                        ->count();
                });
        }

        $this->success('获取成功', $list);
    }



    /**
     * 会议详情
     */
    public function details($id)
    {
        $details = InfoModel::where("id", $id)->find();
        $details->user = User::get(["id" => $details->user_id]);
        $details->is_creator = false;
        if ($details->user_id == $this->auth->id) {
            $details->is_creator = true;
        }
        $Notifications = NotificationsModel::where('meeting_id', $details->id)->count();
        $details->is_notifications = false;
        if ($Notifications > 0) {
            $details->is_notifications = true;
        }
        $details->user_num = AttendeesModel::where('meeting_id', $details->id)
            ->group('user_id')
            ->count();
        $Attendees = AttendeesModel::with(["user", "member"])->where('meeting_id', $details->id)->select();
        foreach ($Attendees as $key => $value) {
            $value->department = DepartmentModel::where("id", $value->member->thee_department_id)->find();
        }
        if ($details->start_time > time()) {
            $details->state = 0; //未开始
        }
        if ($details->start_time < time() && $details->end_time > time()) {
            $details->state = 1; //加入会议/退出会议
        }
        if ($details->end_time < time()) {
            $details->state = 2; //会议结束
        }
        $details["attendees"] = $Attendees;
        $details["sign_num"] = AttendeesModel::where('meeting_id', $details->id)->where("status", 2)->count(); //签到数量

        $this->success('获取成功', $details);
    }

    /**
     * 会议记录列表
     */
    public function minutes_list($id = 0)
    {
        if ($id != 0) {
            $where = [
                "meeting_id" => $id
            ];
        } else {
            $where = [
                "recorder_id" => $this->auth->id
            ];
        }
        $list = MinutesModel::where($where)
            ->order("create_time", "desc")
            ->paginate()
            ->each(function ($minutes, $key) {
                $minutes->user = User::get(["id" => $minutes->recorder_id]);
            });
        $this->success('获取成功', $list);
    }

    /**
     * 会议记录详情
     */
    public function minutes_details($id)
    {
        $minutes = MinutesModel::where("id", $id)->find();
        $minutes->user = User::get(["id" => $minutes->recorder_id]);
        $minutes->member = model("app\admin\model\user\party\Member")->where("user_id", $minutes->recorder_id)->find();
        $minutes->department = DepartmentModel::where("id", $minutes->member->thee_department_id)->find();
        $this->success('获取成功', $minutes);
    }


    /**
     * 会议记录提交
     */
    public function minutes_submit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params['recorder_id'] = $this->auth->id;
            $params['create_time'] = time();
            $record = MinutesModel::insert($params);
            if ($record) {
                $this->success('提交成功');
            }
            $this->error('提交失败');
        }
        $this->error('非法请求');
    }

    /**
     * 会议记录删除
     */
    public function minutes_del($id)
    {

        $delete =  MinutesModel::where("id", $id)->delete();
        if ($delete) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }



    /**
     * 会议通知
     */
    public function notifications($id)
    {

        $details = InfoModel::where("id", $id)->find();
        $details->user = User::get(["id" => $details->user_id]);
        $Attendees = AttendeesModel::with(["user", "member"])->where('meeting_id', $id)->select();
        foreach ($Attendees as $key => $value) {
            $asd = [
                "meeting_id" => $id,
                "title" => "参会通知",
                "content" => "管理员" . $details->user->nickname . "发布了" . $details->title . "的会议，将于" . $details->start_time_text . "开始会议，请您按时参加会议。",
                "user_id" => $value->user_id,
                "create_time" => time()
            ];
            NotificationsModel::insert($asd);
        }
        $this->success('通知成功');
    }



    /**
     * 会议通知列表
     */
    public function notificationslist()
    {
        $notifications = NotificationsModel::where("user_id", $this->auth->id)->where("status", 1)->select();
        $this->success('获取成功', $notifications);
    }

    /**
     * 会议通知列表
     */
    public function notificationslists()
    {
        $notifications = NotificationsModel::where("user_id", $this->auth->id)
            ->paginate();
        $this->success('获取成功', $notifications);
    }


    /**
     * 会议通知详情
     */
    public function notificationsDetails($id)
    {
        $notifications = NotificationsModel::where("id", $id)->find();
        $this->success('获取成功', $notifications);
    }

    /**
     * 会议通知浏览
     */
    public function notificationsSee($id)
    {
        $update = NotificationsModel::where("id", $id)->update(["status" => 2]);
        if ($update) {
            $this->success('浏览成功');
        }
        $this->success('浏览失败');
    }



    /**
     * 生成视频会议链接
     * @return \think\response\Json
     */
    public function create($id)
    {
        // 会议 ID 生成逻辑（可使用随机数或时间戳）
        $meetingId = 'meeting_' . $id;

        // Jitsi Meet 链接
        $domain = "https://8.155.41.240:8444";
        $meetingUrl = "{$domain}/{$meetingId}";

        // 返回会议链接
        return json([
            'code' => 200,
            'message' => '会议创建成功',
            'data' => [
                'meeting_url' => $meetingUrl
            ]
        ]);
    }
}
